import { Component, Prop, Vue } from "vue-property-decorator";
@Component
export default class Diy extends Vue {
  @Prop() private dayEat!: number;
  @Prop() private day!: number;
  // 表单数量
  formNumber = 5;
  // 自定义表单
  form = [{}];
  // 是否禁用添加按钮
  disabledAdd = false;
  // 右边模块显示的内容
  rightContent = "note";
  // 计算表格
  tableData: any[] = [];
  // 百分比警告框
  formError = false;
  // 初始化表单
  restartForm() {
    const form = [];
    for (let i = 0; i < this.formNumber; i++) {
      const obj = {
        foodName: undefined,
        foodRatio: undefined,
      };
      form.push(obj);
    }
    this.form = form;
  }

  // 添加表单数据
  getForm() {
    const arr = this.form;
    const obj = {
      foodName: undefined,
      foodRatio: undefined,
    };
    arr.push(obj);
    this.form = arr;

    if (this.formNumber >= 20) {
      this.disabledAdd = true;
    } else {
      this.disabledAdd = false;
      this.formNumber++;
    }
  }

  // 清空表单
  reset() {
    this.$confirm("此操作将清空表单, 是否继续?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        this.restartForm();
        this.formNumber = 5;
        this.rightContent = "note";
      })
      .catch(() => {
        this.$message({
          type: "info",
          message: "已取消",
        });
      });
  }

  // 提交表单
  submit() {
    const allEat = this.dayEat * this.day;
    this.rightContent = "table";
    const table: any = this.form;
    let percent = 0;
    table.map((item: any) => {
      if (item.foodName !== undefined && item.foodRatio !== undefined) {
        item.needWeight = (allEat * item.foodRatio) / 100;
        percent += item.foodRatio;
      }
    });
    if (percent !== 100) {
      this.formError = true;
    }else{
      this.formError = false;
    }
    const data = table.filter((item: any) => item.foodRatio !== undefined);
    console.log(data);
    this.tableData = data;
  }

  // 格式化表格
  formatRatio(row: any, column: any) {
    // 获取单元格数据
    const data = row[column.property];
    if (data == 0) {
      return 0;
    } else {
      return data + "%";
    }
  }
  // 格式化食材
  formatWeight(row: any, column: any) {
    const num = parseFloat(row[column.property]).toFixed(3);
    const s = num.substring(0, num.length - 1) + "g"; //只取小数位2位
    return (
      s &&
      s.toString().replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
        return $1 + ",";
      })
    );
  }
  created() {
    this.restartForm();
  }
}
